import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-03
 * Time: 15:08
 */
public class TCPEchoServer {
    private ServerSocket serverSocket = null;

    public TCPEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        while (true) {
            Socket clientSocket = serverSocket.accept();//接电话,
            //Socket对象用于和客户一对一服务,ServerSocket用于揽客
            //创建线程,每个线程服务一个客户端
//            Thread t = new Thread(()->{
//                try {
//                    processConnection(clientSocket);//针对一个连接来提供处理逻辑
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
//            //这里的Socket对象:clientSocket是连接级别的数据,需要主动close
//            // 客户端断开连接之和就要close
//            t.start();
            //使用线程池
            ExecutorService service = Executors.newCachedThreadPool();
            service.submit(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                //1.读取请求并且解析
                if (!scanner.hasNext()) {
                    //scanner中无法读取数据,说明客户端关闭了连接,导致服务器端读取到末尾
                    break;
                }
                //2.根据请求计算响应
                String request = scanner.next();
                String response = process(request);
                //3.把响应写回客户端
//                outputStream.write(response.getBytes());
                printWriter.println(response);
                printWriter.flush();//刷新缓冲区
                //4.打印日志
                System.out.printf("[%s:%d] req=%s;rep=%s\n", clientSocket.getInetAddress(), clientSocket.getPort()
                        , request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
        System.out.printf("[%s:%d] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer server = new TCPEchoServer(9090);
        server.start();
    }
}
